import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Cookies from 'js-cookie';
import store from '../store';
import { GetInfoApi } from '../request/api';
// 路径配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login/Login.vue'),
  },
];
const router = createRouter({
  history: createWebHashHistory(), //模式
  routes,
});
// 前置导航守卫 首页每次刷新的时候，重新发送请求将数组存储到vuex里面
router.beforeEach((to, from, next) => {
  const token = Cookies.get('token');
  if (token && store.state.menus.length == 0) {
    // store.dispatch('getInfo');
    GetInfoApi().then((res) => {
      if (res.code == 200) {
        // 存储到vuex
        store.commit('updataMenus', res.data.menus);
        store.commit('updataUserName', res.data.username);
        // vuex 里面获取数据
        const menus = store.getters.getNewMenus;
        for (let key in menus) {
          // 一级菜单对象  menus[key]
          let reuteObj: RouteRecordRaw = {
            path: '/' + menus[key].name,
            name: menus[key].name,
            meta: {
              firstName: menus[key].title,
            },
            component: () => import('../views/Home/Home.vue'),
            children: [],
          };
          // 二级菜单对象
          for (let i = 0; i < menus[key].children.length; i++) {
            reuteObj.children!.push({
              path: menus[key].children[i].name,
              name: menus[key].children[i].name,
              meta: {
                SeconName: menus[key].children[i].title,
              },
              component: () =>
                import(
                  `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
                ),
            });
          }
          // 动态添加路由
          router.addRoute(reuteObj);
        }
        // 路由重定向到index
        router.addRoute({
          path: '/',
          name: 'home',
          redirect: '/index',
          component: () => import('../views/Home/Home.vue'),
          children: [
            {
              path: 'index',
              name: 'index',
              component: () => import('../views/index/index.vue'),
            },
          ],
        });
      }
      next(to);
    });
  } else if (!token && to.path !== '/login') {
    next('/login');
  } else if (token && to.path === '/login') {
    next(from);
  } else {
    next();
  }
});
export default router;
